var DragAndDrop = {
  activity : {},

  edit : function(activity) {
    this.activity = activity;
    var subtype = activity["subtype"];
    if (!subtype) {
      subtype = "images";
      Activity.editProperty(activity["id"], "subtype", subtype);
    }
    switch (subtype) {
      case "images": this.editImages(); break;
      case "isotopes" : this.editIsotopes(); break;
    }
    if (subtype == "images") {
      this.editImages();
    } else if (subtype == "isotopes") {
      this.editIsotopes();
    } else if (subtype == "squares") {
      $("button.create-reaction").show();
    }
  },

  editImages : function() {
    $("button.select-periodic-square, button.create-reaction, div#isotopes, a.clear-isotope-selection").hide();
    var images = this.activity["image"];
    if (!images || images.length < 4) {
      $("button.add-image").show();
    }
    var draggables = $("div#draggables");
    draggables[0].innerHTML = "";
    var table = "<table><tr>";
    if (images) {
      for (var i = 0; i < images.length; i++) {
        var image = images[i];
        var category = image["category"];
        table += "<td><img src=\"" + image["url"] + "\" width=\"200px\" /><br />" +
          "<textarea class=\"category\" id=\"category_" + image["id"] + "\" " +
          "onblur=\"DragAndDrop.saveImageCategory('" + image["id"] + "')\">" +
          (category ? category : "Category") + "</textarea></td>";
      }
      table += "</tr></table>";
      draggables.append(table);
    }
  },

  editIsotopes : function() {
    $("button.add-image, button.select-periodic-square, button.create-reaction").hide();
    $("div#isotopes, a.clear-isotope-selection").show();
    var isotopes = this.activity["isotope"];
    if (isotopes) {
      for (var i = 0; i < isotopes.length; i++) {
        var isotope_id = isotopes[i].value;
        var isotope = $("canvas#" + isotope_id)[0];
        $(isotope).addClass("selected");
        isotope.getContext("2d").strokeRect(10, 10, isotope.width - 20, isotope.height - 20);
      }
    }
  },

  editSquares : function() {
    $("button.add-image, button.create-reaction, div#isotopes, a.clear-isotope-selection").hide();
    var squares = this.activity["squares"];
    if (!squares) {
      $("button.select-periodic-square").show();
    }
    var draggables = $("div#draggables");
    draggables[0].innerHTML = "";
    if (squares) {
      for (var i = 0; i < squares.length; i++) {

      }
    }
  },

  editMolecules : function() {
    $("button.add-image, button.select-periodic-square, div#isotopes, a.clear-isotope-selection").hide();
    var molecules = this.activity["molecules"];
    if (!molecules) {
      $("button.create-reaction").show();
    }
    var draggables = $("div#draggables")
    draggables.innerHTML = "";
    if (molecules) {
      for (var i = 0; i < molecules.length; i++) {

      }
    }
  },

  play : function(activity) {
    this.activity = activity;
    switch (activity["subtype"]) {
      case "images" : this.playImages(); break;
      case "isotopes" : this.playIsotopes(); break;
    }
  },

  playImages : function() {
    var images = this.activity["image"];
    var categories = $.map(images, function(n, i) {
      return { name : n["category"], id : n["id"] };
    });
    images = shuffle(images);
    var target = $("#play_drag_and_drop");
    target[0].innerHTML = "";
    var table = "<table><tr>";
    for (var i = 0; i < images.length; i++) {
      var img = images[i];
      table += "<td><div ondragstart='dnd.start(event)' " +
        "ondrag='dnd.drag(event)' ondragend='dnd.dragEnd(event)'>" +
        "<img id='img_" + img["id"] + "' src='" + img.url +
        "' data-value='" + img["id"] + "' style='width:200px' /></div></td>";
    }
    table += "</tr><tr>";
    for (var j = 0; j < categories.length; j++) {
      var category = categories[j];
      table += "<td class='category a-center'><div class='drop-target' " +
        "ondragover='dnd.over(event)' ondrop='dnd.drop(event)'>" +
        " Drag and drop<br />the correct<br />image here</div>" +
        "<p id='category_" + category["id"] + "' class='category-name large'>" + category.name + "</p></td>"
    }
    table += "</tr></table>";
    target.append(table);
    dnd.setStartCallBack(function() {
//      alert("start!");
    });
    dnd.setDropCallBack(function() {
      var img = $("#img_" + dnd.value)
      dnd.target.innerHTML = "";
      $(dnd.target).append(img.parent().html());
      img.hide();
    });
  },

  playIsotopes : function() {
    var canvases = $("canvas.isotope");
    for (var i = 0; i < canvases.length; i++) {
      var ctx = canvases[i].getContext("2d");
      ctx.clearRect(0, 0, canvases[i].width, canvases[i].height);
      var x = 0.5 * canvases[i].width;
      var y = 0.5 * canvases[i].height;
      var scale = 0.333 * canvases[i].width;
      i2a(canvases[i].id).drawAtomicModel(ctx, x, y, scale, false, true);
      $(canvases[i]).show();
    }

    var isotopes = this.activity["isotope"];
    var answers = $("td.answer");
    for (var j = 0; j < answers.length && j < isotopes.length; j++) {
      var id = isotopes[(j + 2) % isotopes.length].value;
      var a = i2a(id);
      var answer = answers[j];
      answer.innerHTML = "<canvas id='answer_" + id + "' width='200' height='200'></canvas>" +
        "<p class='a-center'>Atomic weight = " + (Number(a.protons) + Number(a.neutrons)) +
        "<br /># of neutrons = " + a.neutrons + "</p>";
    }
    dnd.setStartCallBack(function() {});
    dnd.setDropCallBack(function(target, value) {
      if (target instanceof HTMLCanvasElement) {
        if (!$(target).attr("drawn")) {
          var a = i2a(value);
          var ctx = target.getContext("2d");
          ctx.clearRect(0, 0, target.width, target.height);
          var x = 0.5 * target.width;
          var y = 0.5 * target.height;
          var scale = 0.333 * target.width;
          a.drawAtomicModel(ctx, x, y, scale, false, true);
          $(target).attr("drawn", value);
          $(dnd.source).hide();
        }
      }
    });
  },

  score : function() {
    switch (this.activity["subtype"]) {
      case "images" : this.scoreImages(); break;
      case "isotopes" : this.scoreIsotopes(); break;
    }
  },

  scoreImages : function() {
    var categories = $('.category');
    var mistakes = "";
    for (var i = 0; i < categories.length; i++) {
      var category = $(categories[i]).find("p.category-name")[0];
      var category_id = category.id.substring("category_".length);
      var category_name = category.innerHTML;

      var img = $(categories[i]).find("img")[0];
      if (img) {
        var img_id = img.id.substring("img_".length);
        if (category_id != img_id) {
          mistakes += "Incorrect image for the category " + category_name + ".\n";
        }
      } else {
        mistakes += "No image selected for the category " + category_name + ".\n";
      }
    }
    if (mistakes.length > 0) {
      alert(mistakes);
      this.reset();
    } else {
      alert("You passed this activity.");
    }
  },

  scoreIsotopes : function() {
    var answers = $("td.answer");
    var pass = true;
    for (var j = 0; j < answers.length; j++) {
      var canvas = $(answers[j]).find("canvas")[0];
      var correct = canvas.id.substring("answer_".length);
      var drawn = $(canvas).attr("drawn");
      if (correct != drawn) {
        pass = false;
      }
    }
    alert(pass ? "You have passed this activity." : "Try again.");
    if (!pass) {
      this.reset();
    }
  },

  reset : function() {
    if (this.activity) {
      this.play(this.activity);
    }
  },

  saveImageCategory : function(image_id) {
    var value = $("textarea#category_" + image_id)[0].value;
    image.editProperty(image_id, "category", value);
  },

  selectIsotope : function(isotope_id) {
    var isotope = $("canvas#" + isotope_id);
    if ($(isotope[0]).hasClass("selected")) {
      return;
    }
    var activity = DragAndDrop.activity;
    Activity.createChild(activity["id"], "isotope", JSON.stringify( { "value" : isotope_id } ));
    if (!activity["isotope"]) {
      activity["isotope"] = [];
    }
    if (activity["isotope"].length >= 4) {
      return;
    }
    activity["isotope"].push( { "value" : isotope_id } );
    this.editIsotopes();
  },

  changeSubtype : function(subtype) {
    Activity.editProperty(this.activity["id"], "subtype", subtype);
    if (subtype == "images") {
      this.editImages(this.activity["image"]);
    } else if (subtype == "isotopes") {
      this.editIsotopes()
    } else if (subtype == "squares") {
      this.editSquares()
    } else if (subtype == "molecules") {
      this.editMolecules();
      $("button.add-image").hide();
      $("button.select-periodic-square").hide();
      $("button.create-reaction").show();
    }
  },

  toHTML : function(activity) {
    var html = "";
    if (activity["subtype"] == "Images") {
      var images = activity["image"];
      html += "<table><tr>";
      for (var i = 0; i < images.length; i++) {
        var src = images[i]["url"];
        html += "<td><img src=\"" + src + "\" /></td>";
      }
      html += "</tr></table>";
    }
  }
};